<template>
  <div class="store-container">
    <div class="store-header">
      <h2>店铺管理</h2>
      <el-button type="primary" @click="handleAdd">添加店铺</el-button>
    </div>

    <el-table
      v-loading="loading"
      :data="paginatedStoreList"
      style="width: 100%"
      border
      max-height="600"
      :scrollbar-always-on="true"
    >
      <el-table-column prop="id" label="店铺ID" width="80" />
      <el-table-column label="店铺Logo" width="120" align="center">
        <template #default="{ row }">
          <el-image
            v-if="row.logo"
            :src="row.logo"
            style="width: 80px; height: 80px; object-fit: cover;"
            :preview-src-list="[row.logo]"
            fit="cover"
          />
          <span v-else>暂无Logo</span>
        </template>
      </el-table-column>
      <el-table-column prop="storeName" label="店铺名称" min-width="150" show-overflow-tooltip />
      <el-table-column prop="userId" label="店主ID" width="100" />
      <el-table-column prop="follower_count" label="关注人数" width="100" align="center" />
      <el-table-column prop="description" label="店铺描述" min-width="200" show-overflow-tooltip />
      <el-table-column label="创建时间" width="180">
        <template #default="{ row }">
          {{ formatTime(row.create_at) }}
        </template>
      </el-table-column>
      <el-table-column label="状态" width="100" align="center">
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'danger'">
            {{ row.status === 1 ? '正常' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button
            type="primary"
            link
            @click="handleEdit(row)"
          >
            编辑
          </el-button>
          <el-button
            type="danger"
            link
            @click="handleDelete(row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        :current-page="currentPage"
        :page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加/编辑店铺对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="店铺名称" prop="storeName">
          <el-input v-model="formData.storeName" placeholder="请输入店铺名称" />
        </el-form-item>
        <el-form-item label="店主ID" prop="userId" v-if="!isEdit">
          <el-input v-model="formData.userId" placeholder="请输入店主ID" />
        </el-form-item>
        <el-form-item label="店铺Logo" prop="logo">
          <el-input v-model="formData.logo" placeholder="请输入Logo图片URL" />
        </el-form-item>
        <el-form-item label="店铺封面" prop="cover">
          <el-input v-model="formData.cover" placeholder="请输入封面图片URL" />
        </el-form-item>
        <el-form-item label="店铺描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="3"
            placeholder="请输入店铺描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getAllStore, addStore, updateStore, delStore } from '../../api/store'

const loading = ref(false)
const storeList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 分页后的店铺列表
const paginatedStoreList = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return storeList.value.slice(start, end)
})

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
}

// 处理每页数量变化
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1 // 重置到第一页
}
const dialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref(null)

const formData = ref({
  storeName: '',
  userId: '',
  logo: '',
  cover: '',
  description: ''
})

const formRules = {
  storeName: [
    { required: true, message: '请输入店铺名称', trigger: 'blur' }
  ],
  userId: [
    { required: true, message: '请输入店主ID', trigger: 'blur' }
  ]
}

const dialogTitle = computed(() => isEdit.value ? '编辑店铺' : '添加店铺')

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  try {
    const date = new Date(time)
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
      hour12: false
    }).replace(/\//g, '-')
  } catch (e) {
    console.error("时间格式化错误:", e)
    return time
  }
}

// 获取店铺列表
const fetchStoreList = async () => {
  try {
    loading.value = true
    const res = await getAllStore()
    if (res.status === 0) {
      storeList.value = res.data
      // 更新总数
      total.value = storeList.value.length
      // 重置到第一页
      currentPage.value = 1
    } else {
      ElMessage.error(res.message || '获取店铺列表失败')
    }
  } catch (error) {
    console.error('获取店铺列表错误:', error)
    ElMessage.error('获取店铺列表失败')
  } finally {
    loading.value = false
  }
}

// 添加店铺
const handleAdd = () => {
  isEdit.value = false
  formData.value = {
    storeName: '',
    userId: '',
    logo: '',
    cover: '',
    description: ''
  }
  dialogVisible.value = true
}

// 编辑店铺
const handleEdit = (row) => {
  isEdit.value = true
  formData.value = {
    id: row.id,
    storeName: row.storeName,
    logo: row.logo,
    cover: row.cover,
    description: row.description
  }
  dialogVisible.value = true
}

// 删除店铺
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确定要删除该店铺吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const res = await delStore({ id: row.id })
      if (res.status === 0) {
        ElMessage.success('删除店铺成功')
        await fetchStoreList()
      } else {
        ElMessage.error(res.message || '删除店铺失败')
      }
    } catch (error) {
      console.error('删除店铺错误:', error)
      ElMessage.error('删除店铺失败')
    }
  }).catch(() => {})
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const api = isEdit.value ? updateStore : addStore
        const res = await api(formData.value)
        
        if (res.status === 0) {
          ElMessage.success(isEdit.value ? '更新店铺成功' : '添加店铺成功')
          dialogVisible.value = false
          await fetchStoreList()
        } else {
          ElMessage.error(res.message || (isEdit.value ? '更新店铺失败' : '添加店铺失败'))
        }
      } catch (error) {
        console.error(isEdit.value ? '更新店铺错误:' : '添加店铺错误:', error)
        ElMessage.error(isEdit.value ? '更新店铺失败' : '添加店铺失败')
      }
    }
  })
}

onMounted(() => {
  fetchStoreList()
})
</script>

<style scoped>
.store-container {
  padding: 20px;
}

.store-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.store-header h2 {
  margin: 0;
  font-size: 20px;
  color: #333;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  padding: 10px 0;
  display: flex;
  justify-content: flex-end;
}
</style>